package cn.lwj.webService.interceptor;

import java.util.List;
import javax.xml.namespace.QName;
import org.apache.cxf.binding.soap.SoapHeader;
import org.apache.cxf.binding.soap.SoapMessage;
import org.apache.cxf.headers.Header;
import org.apache.cxf.helpers.DOMUtils;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class SOAPHeaderInterceptor extends AbstractPhaseInterceptor<SoapMessage> {

	public static final String namespaceUR_att = "http://webservice.withub.net.cn//authentication";  
	public static final String header_el = "Header";
	public static final String authentication_el = "authentication";
	public static final String username_el = "username";
	public static final String password_el = "password";
	public static final String court_el = "fydm";
	public String username = "";
	public String password = "";
	public String fydm = "";

	public SOAPHeaderInterceptor(String fydm, String username, String password) {
		super(Phase.PRE_PROTOCOL);
		this.username=username;
		this.password=password;
		this.fydm=fydm;
	}

	public void handleMessage(SoapMessage message) throws Fault {
		QName qname = new QName(header_el); 
		Document doc = (Document) DOMUtils.createDocument();
		Element root = doc.createElement(header_el);
		Element eUserId = doc.createElement(username_el);
		eUserId.setTextContent(username);
		Element ePwd = doc.createElement(password_el);
		ePwd.setTextContent(password);
		Element eFy = doc.createElement(court_el);
		eFy.setTextContent(fydm);
		Element child = doc.createElementNS(namespaceUR_att,authentication_el);
		child.appendChild(eUserId);
		child.appendChild(ePwd);
		child.appendChild(eFy);
		root.appendChild(child);
//		XMLUtils.printDOM(root);//打印XML到控制台
		SoapHeader head = new SoapHeader(qname, root);
		List<Header> headers = message.getHeaders();
		headers.add(head);
	}
}
